How to Secure Your Server with UFW and iptables: A Beginner's Guide to Linux Firewalls

Giteqa

Greetings, friends!

Configuring a network firewall is the primary and most vital step in securing any virtual server. Unprotected and open network ports quickly become targets for automated scanners, brute-force attacks, and exploitation attempts targeting system services.

In Linux operating systems, packet filtering is handled at the kernel level by the netfilter subsystem. To interact with it, administrators rely on two primary tools: the powerful, low-level iptables utility suite and UFW (Uncomplicated Firewall), a user-friendly wrapper designed to simplify daily administration. In this article, we will cover the fundamental operating principles of both solutions.

Key Takeaways: Core Conclusions

  • UFW is the standard for routine tasks: UFW offers a clean, human-readable syntax that prevents fatal configuration mistakes when opening ports for SSH, web servers, or databases on Ubuntu and Debian.

  • iptables provides low-level power: iptables gives you complete control over packet chains, Network Address Translation (NAT), port forwarding, and custom filtering rules at the kernel layer.

  • The golden firewall rule is Default Deny: A robust firewall configuration follows a strict policy: "deny everything that is not explicitly allowed." All incoming traffic is blocked by default, except for essential services (such as SSH and HTTP/HTTPS).

Part 1. Setting Up UFW (Uncomplicated Firewall)

UFW comes pre-installed on Ubuntu and is readily available in the official repositories of most major Linux distributions.

Step 1: Check Status and Define Base Policy

Before enabling the firewall, set the default policies to block incoming connections and permit outgoing traffic:

Bash
sudo ufw default deny incoming
sudo ufw default allow outgoing

Step 2: Allow Essential Ports

CRITICAL: Always allow SSH access before enabling UFW; otherwise, you will immediately lock yourself out of your server!

Bash
# Allow SSH on default port 22
sudo ufw allow 22/tcp

# Alternatively, allow SSH by service name
sudo ufw allow ssh

# Allow web traffic (HTTP & HTTPS)
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

Step 3: Enable UFW and Manage Rules

Bash
# Enable the firewall
sudo ufw enable

# View current status and active rules with line numbers
sudo ufw status numbered

# Delete a rule by its corresponding number (e.g., rule #3)
sudo ufw delete 3

# Rate-limit SSH logins to mitigate brute-force attempts
sudo ufw limit ssh

Part 2. Understanding iptables Basics

iptables structures its logic using Tables and Chains. Standard packet filtering takes place within the filter table across three built-in chains:

  • INPUT: Traffic originating externally and destined directly for the server itself.

  • OUTPUT: Traffic generated locally by the server heading outward.

  • FORWARD: Traffic passing transitively through the server (e.g., when acting as a router or VPN gateway).

Plaintext
[ Network Packet ] ---> INPUT (Server) ---> FORWARD (Transit) ---> OUTPUT (Egress)

Essential iptables Commands

1. Inspect Active Rules

Bash
sudo iptables -L -v -n
  • -v provides verbose output (showing byte and packet counters).

  • -n displays IP addresses and port numbers numerically, bypassing DNS resolution delays.

2. Permit Loopback and Established Connections

The server must be able to communicate with itself via the loopback interface (lo) and maintain active state connections:

Bash
sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

3. Open Specific Service Ports

Bash
# Allow incoming SSH connections (Port 22)
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# Allow HTTP (80) and HTTPS (443)
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT

4. Set Default Drop Policy

After explicitly accepting necessary connections, set the default chain policy to drop all other incoming traffic:

Bash
sudo iptables -P INPUT DROP

5. Reset All Rules (Flush)

If you accidentally lock a required port and need to clear your configuration back to defaults:

Bash
sudo iptables -F
sudo iptables -P INPUT ACCEPT

Comparison Matrix: UFW vs iptables

Evaluation CriterionUFWiptables
Complexity LevelLow (intuitive, simple syntax)Medium / High
Target AudienceBeginners and system administratorsExperienced engineers, DevOps, network architects
Configuration FlexibilityTailored for common, standard scenariosComplete (custom chains, packet marking, NAT, MANGLE)
NAT / Port Forwarding SupportRequires manually editing configuration filesNative support via the nat table
Rule PersistenceYes (saves state automatically)No (requires iptables-persistent package)

FAQ: Frequently Asked Questions

  • Can I use UFW and iptables at the same time?

    UFW operates as a user-friendly interface over iptables (or nftables in modern kernels). Manually modifying iptables rules while UFW is active is not recommended, as UFW reloads can overwrite your custom manual chains.

  • What should I do if I lock myself out of SSH via iptables or UFW?

    If you lose SSH access, open your hosting provider's management console and connect using the Emergency Console (VNC or Out-of-Band IPMI). Once logged in, disable the firewall using sudo ufw disable or reset iptables rules with sudo iptables -F.

  • How do I make iptables rules persist across server reboots?

    By default, iptables rules applied via the command line clear when the system restarts. To save them permanently on Ubuntu or Debian, install the iptables-persistent package:

    Bash
    sudo apt install iptables-persistent -y
    sudo netfilter-persistent save
    

Conclusion

A well-configured firewall forms the essential baseline for securing any server exposed to the internet. For 95% of routine web development and system administration tasks, UFW provides more than enough functionality. Meanwhile, iptables remains an indispensable tool for complex routing architectures and specialized packet filtering.

However, even the strictest firewall rules cannot protect your server if it faces massive volumetric network attacks (DDoS) at the carrier level that saturate your provider's network ports.

If you are looking for a secure, resilient infrastructure for your projects, explore NVMe VPS and Hourly Cloud Servers from MivoCloud. We provide pure KVM virtualization, guaranteed compute resources, a protected network infrastructure, and high-performance Enterprise NVMe storage to keep your services running flawlessly.


Article Author: Anatolie Cohaniuc